import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Popover, DatePicker, Select, TreeSelect,
} from 'antd';

import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';

import debounce from 'lodash/debounce';
import { ellipsis, popoverPrice, renderTreeNodes,popoverBling } from '@/utils/utils';
import Detail from './../Owner/Detail';
import './../Home/openlayers.less';
import ReactDataGrid from 'react-data-grid';
import gold from './../../images/gold.png'
import request from '@/utils/request';
import AreaMap from "@/components/AreaMap";
const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;

@connect(({ billings, loading,global }) => ({
  billings,
  global,
  loading: loading.models.billings,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      data:[],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      billings: { pageLoaded, scrollData },
    } = this.props;

    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        billings: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'billings/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'billings/changeLoaded',
          });
          dispatch({
            type: 'billings/changeTableY',
          });
        },
      });

    }
    const that=this;
    request(`/all_regions`,{
      method:'GET',
    }).then((response)=>{
      if(response.status===200){
        that.setState({
          data:response.data.data
        })
      }

    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    // document.addEventListener('keyup',this.keyupFunc)
  }
  keyupFunc=(e)=>{
    if(e.keyCode===13) {
      this.searchFunc()
    }
  }
  searchFunc=()=>{
    const { form, billings: { searchParams} } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.handleSearch({
        page: 1,
        per_page: searchParams.per_page,
        ...fieldsValue,
        start_date: fieldsValue.start_date ? moment(fieldsValue.start_date).format('YYYY-MM-DD') : '',
        end_date: fieldsValue.end_date ? moment(fieldsValue.end_date).format('YYYY-MM-DD') : '',
      });

    });
  }
  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'billings/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'billings/changeTableY',
    });
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    // document.removeEventListener('keyup',this.keyupFunc);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }
  findChildFunc = (cb)=> {
    this.findChildLocation = cb
  }
  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'billings/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const data=this.state.data
    const {
      billings: { searchParams },
    } = this.props;
    const form=this.props.form
    const getFieldDecorator=form.getFieldDecorator
    return (
      <Form layout="inline" className="search-form">
        <AreaMap form={form} searchParams={searchParams} getFieldDecorator={getFieldDecorator}/>
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: searchParams.start_date ? moment(searchParams.start_date) : '',
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: searchParams.end_date ? moment(searchParams.end_date) : '',
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label="类型">
          {getFieldDecorator('type', {
            initialValue: searchParams.type,
          })(
            <Select style={{width:'120px'}}>
              {
                [{id:'',value:'全部'},{id:'1',value:'阶梯收费'},{id:'2',value:'污水处理费'}].map((item,index)=>{
                  return <Option key={index} value={item.id}>{item.value}</Option>
                })
              }
            </Select>
          )}
        </FormItem>
        <FormItem label="区域">
          {getFieldDecorator('region_id', {
            initialValue: searchParams.region_id,
          })(
            <TreeSelect
              style={{width:'120px'}}
              allowClear
            >
              {renderTreeNodes(data)}
            </TreeSelect>
          )}
        </FormItem>
        <FormItem label="所属片区">
          {getFieldDecorator('region_area', {
            initialValue: searchParams.region_area,
          })(<Select style={{width:'90px'}}  allowClear={true}>
            <Option value={'A片区'}>A片区</Option>
            <Option value={'B片区'}>B片区</Option>
            <Option value={'C片区'}>C片区</Option>
            <Option value={'D片区'}>D片区</Option>
          </Select>)}
        </FormItem>
        <FormItem label="户主姓名">
          {getFieldDecorator('name', {
            initialValue: searchParams.name,
          })(<Input style={{ width: '120px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="户主手机">
          {getFieldDecorator('mobile', {
            initialValue: searchParams.mobile,
          })(<Input style={{ width: '120px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem label="水表号">
          {getFieldDecorator('meter_number', {
            initialValue: searchParams.meter_number,
          })(<Input style={{ width: '150px' }} placeholder="请输入"  onKeyPress={this.keyPress}/>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              this.searchFunc()
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        this.searchFunc()
      });
    }
  }

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD"),
      end_date:moment(new Date()).format('YYYY-MM-DD'),
      region_id:"",
      region_area:"",
      name:'',
      mobile:'',
      meter_number:'',
      operator_name:'',
      type:'',
      page: 1,
      per_page: 50,
    });
  };

  renderStatus = (val) => {
    let type = '';
    let color = '';
    let text = '';
    switch (val) {
      case 1:
        type = 'close-circle', color = '#00da4a', text = '在线';
        break;
      case -1:
        type = 'close-circle', color = '#fe1b2e', text = '离线';
        break;
      default:
        type = 'close-circle', color = '#eb2f96', text = '异常';
        break;
    }
    return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
  };

  render() {
    const that = this;
    const {
      billings: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global:{gridTableW}
    } = this.props;
    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen:true,
        formatter: (event) => {
          const {
            billings: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page-1)*meta.per_page)+(event.value+1)}</p>
        }
      },
      {
        name: '扣费时间',
        width: 165,
        key: 'current_billing_time',
        frozen:true,
      },
      {
        name: '户主姓名',
        key: 'name',
        width: 150,
        frozen:true,
        formatter:(event)=>{
          return <span title={event.row.account.name}>{event.row.account.name}</span>
        }
      },
      {
        name: '扣费金额',
        width: 120,
        key: 'amount',
        frozen:true,
        formatter:(event)=>{
          return <Popover title={event.value} content={popoverBling(event.row)}>
            <div className={`money`}><img className={'gold'} src={gold} alt=""/>{event.value}</div>
          </Popover>
        }
      },
      {
        name: '当天余额',
        width: 100,
        key: 'balance',
        formatter: (event) => {
          return <p
            className={Number(event.row.account.balance) > 0 ? 'table-success table-status' : 'table-error table-status'}>{event.row.account.balance}</p>;
        },
      },
      {
        name: '扣费水量(m3)',
        width: 120,
        key: 'consumption',
      },

      {
        name: '户主手机',
        key: 'mobile',
        width: 130,
        formatter:(event)=>{
          return event.row.account.mobile
        }
      },
      {
        name: '水表号',
        width: 135,
        key: 'meter_number',
        formatter:(event)=>{
          return event.row.account.meter_number
        }
      },
      {
        name: '区域名称',
        width: 150,
        key: 'upload_time22',
        formatter:(event)=>{
          return <span title={event.row.account.region.name}>{event.row.account.region.name}</span>
        }
      },
      {
        name: '用水性质',
        width: 155,
        key: 'price_nature',
        formatter:(event)=>{
          return <Popover title={event.row.account.price_nature.name} content={popoverPrice(event.row.account.price_nature)}>
            {event.row.account.price_nature.name}
          </Popover>
        }
      },
      {
        name: '计费人数',
        width: 120,
        key: 'people_number',
      },
      {
        name: '操作',
        width: 120,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          <Button
            type="primary"
            icon="eye"
            size="small"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >水表详情
          </Button>
        </Fragment>,
      },
    ].map(c => ({  ...defaultColumnProperties,...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if(totalWidth<gridTableW){
      columns[columns.length-1].width=   columns[columns.length-1].width+gridTableW-totalWidth
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>扣费记录</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {return {...data[i],_index:i}}}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                if(!String(row)){
                  return
                }
                this.props.dispatch({
                  type: 'billings/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading&&<Loading />
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');
                        const {
                          billings: { scrollData },
                        } = this.props;
                        const table = document.querySelector('.react-grid-Canvas');
                        setTimeout(() => {
                          table.scrollTop = 0;
                          table.scrollLeft = scrollData.x;
                        }, 0);

                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`${this.state.editRecord.account && this.state.editRecord.account.name} 详情`}
        placement="right"
        destroyOnClose
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}

        width={780}
        visible={this.state.infoModal}
      >
        <Detail meter_number={this.state.editRecord.account&&this.state.editRecord.account.meter_number}
                id={this.state.editRecord.account&&this.state.editRecord.account.id}></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
